package com.leo.base_project.activity.login;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.leo.base_project.R;
import com.leo.base_project.Utils.UIUtils;
import com.leo.base_project.activity.base.BaseActivityX;
import com.leo.base_project.entity.User;
import com.leo.base_project.entity.UserDao;

import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RegActivity extends BaseActivityX {

    @BindView(R.id.ed_login_username)
    EditText edUsername;
    @BindView(R.id.ed_login_password)
    EditText edPassword;

    UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        ButterKnife.bind(this);
        userDao = daoSession.getUserDao();
    }

    public void reg(View view) {
        // 判断空
        String username = edUsername.getText().toString();
        String password = edPassword.getText().toString();
        if (StringUtils.isBlank(username)){
            UIUtils.toast("用户名不能为空");
            return;
        }
        if (StringUtils.isBlank(password)){
            UIUtils.toast("密码不能为空");
            return;
        }
        // 判断用户名是否存在
        User user = getUserByUsername(username);
        if (user != null){
            UIUtils.toast("用户已存在");
            cleanInput();
            return;
        }
        // 判断用户名和密码是否正确
        User regUser = new User();
        regUser.setUsername(username);
        // todo 是否需要加密？
        regUser.setPassword(password);
        regUser.setRegDate(new Date());
        userDao.save(regUser);
        UIUtils.toast("注册成功");
        finish();
    }

    private User getUserByUsername(String username) {
        // 少一点的时候可以这么操作
        List<User> users = userDao.loadAll();
        for (User user:users){
            if (user.getUsername().equals(username)){
                return user;
            }
        }
        return null;
    }

    private void cleanInput(){
        edUsername.setText("");
//        edPassword.setText("");
    }
}